package com.laolang.shop.modules.auth.evaluator.impl;

import cn.hutool.core.util.StrUtil;
import com.laolang.shop.modules.auth.consts.AuthConst;
import com.laolang.shop.modules.auth.evaluator.AdminPermissionEvaluator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * khl 自定义 多参数SPEL
 * 参考:
 * http://www.voidcn.com/article/p-erljkmyc-bte.html
 * https://stackoverflow.com/questions/26747452/how-to-use-custom-expressions-in-spring-security-preauthorize-postauthorize-an
 *
 * @author khlbat
 * @version 1.0
 * @date 2020/11/1 20:46
 */
@Slf4j
@Component("adminPerm")
public class AdminPermissionEvaluatorImpl implements AdminPermissionEvaluator {
    @Override
    public boolean isAdmin(Authentication authentication) {
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        boolean isAdmin = false;
        for (GrantedAuthority authority : authorities) {
            if (StrUtil.equals(AuthConst.PERM_ADMIN, authority.getAuthority())) {
                isAdmin = true;
                break;
            }
        }
        return isAdmin;
    }
}
